package initialize

import (
	"encoding/json"
	"github.com/fsnotify/fsnotify"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"userop_bff/global"
)

func InitConfig() {
	viper.SetConfigFile("./appconfig/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		zap.S().Panic(err)
	}
	err = viper.Unmarshal(&global.ServerConfig)
	if err != nil {
		zap.S().Panic(err)
	}
	go func() {
		viper.OnConfigChange(func(e fsnotify.Event) {
			err = viper.Unmarshal(&global.ServerConfig)
			if err != nil {
				zap.S().Panic(err)
			}
			zap.S().Info(global.ServerConfig)
		})
		viper.WatchConfig()
	}()
	//动态读取nacos配置中信息
	InitNaCos()
}

func InitNaCos() {
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.ServerConfig.NaCosConfig.NameSpaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.ServerConfig.NaCosConfig.Host,
			ContextPath: "/nacos",
			Port:        uint64(global.ServerConfig.NaCosConfig.Port),
			GrpcPort:    uint64(global.ServerConfig.NaCosConfig.GrpcPort),
		},
	}
	// Create config client for dynamic configuration
	client, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	config, _ := client.GetConfig(vo.ConfigParam{
		DataId: global.ServerConfig.NaCosConfig.DataId,
		Group:  global.ServerConfig.NaCosConfig.Group})

	json.Unmarshal([]byte(config), &global.ServerConfig)
}
